// pages/orderDetail.js
const util = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order: null,
    loading: false,
    showTimePicker: false,
    timeRanges: [
      '08:00-09:00',
      '09:00-10:00',
      '10:00-11:00',
      '11:00-12:00',
      '12:00-13:00',
      '13:00-14:00',
      '14:00-15:00',
      '15:00-16:00',
      '16:00-17:00',
      '17:00-18:00',
      '18:00-19:00',
      '19:00-20:00'
    ], // 可选时间范围
    selectedTimeRange: null // 选中的时间范围
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 如果有传入订单ID，则加载对应订单数据
    if (options && options.id) {
      this.loadOrderData(options.id, options.pay);
    } else {
      // 使用示例数据
      this.formatOrderData();
    }
    console.log(this.data)
  },

  /**
   * 加载订单数据
   */
  loadOrderData(orderId, topay) {
    this.setData({
      loading: true
    });

    // 服务器获取订单数据
    util.callContainerApi(`/order/info?orderId=${orderId}`, "GET", null)
      .then(res => {
        let order = res.data.data.order
        const merchantList = wx.getStorageSync('merchantList')
        for (const item of merchantList) {
          if (item.id === order.merchantId) {
            order.merchantName = item.merchantName
          }
        }
        let childs = res.data.data.childs
        for (let child of childs) {
          if(child.merchandiseId > 540){
            // 之后上传的图片没有后缀
            child.fileId = `cloud://prod-8g6k5cfre7cd634b.7072-prod-8g6k5cfre7cd634b-1363249267/${child.merchandiseId}`
          } else {
            child.fileId = `cloud://prod-8g6k5cfre7cd634b.7072-prod-8g6k5cfre7cd634b-1363249267/${child.merchandiseId}.jpg`
          }
        }
        if (order.createAt) {
          order.createTime = util.formatTime(order.createAt)
        }
        if (order.payAt) {
          order.payTime = util.formatTime(order.payAt)
        }
        if (order.finishAt) {
          order.finishTime = util.formatTime(order.finishAt)
        }
        this.setData({
          "order": order,
          "childs": childs,
          "loading": false,
        })
        if (topay) {
          this.payOrder()
        }
        console.log(childs)
      }).catch(res => {
        console.error('获取订单详情失败', err);
        wx.showToast({
          title: '获取订单失败',
          icon: 'error'
        });
        this.setData({
          loading: false
        });
      })

    this.setData({
      loading: false
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查是否从地址选择页面返回
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];

    // 如果有选择的地址，则更新订单地址信息
    if (currentPage.data.selectedAddress) {
      this.updateOrderAddress(currentPage.data.selectedAddress);
      // 清除选择的地址，避免重复更新
      currentPage.data.selectedAddress = null;
    }
  },

  /**
   * 编辑收货地址
   */
  editAddress() {
    // 跳转到地址列表页面
    const {
      order
    } = this.data
    const self = this
    wx.navigateTo({
      url: '/pages/addressList/addressList?selectMode=true',
      events: {
        selectAddressInfo: function (data) {
          util.callContainerApi(`/order/changeadd?orderId=${order.id}&addressId=${data.data.id}`, "POST")
            .then((res) => {
              order.receiveName = data.data.receiveName
              order.region = data.data.region
              order.address = data.data.address
              order.phone = data.data.phone
              self.setData({
                "order": order
              })
            })
        }
      }
    })
  },

  /**
   * 显示时间选择器
   */
  editDeliveryTime() {
    // 初始化时间范围

    this.setData({
      showTimePicker: true
    });
  },

  /**
   * 时间选择器变化
   */
  bindTimePickerChange(e) {
    const index = e.currentTarget.dataset.value;
    const selectedRange = this.data.timeRanges[index];

    // 更新选中状态
    this.setData({
      selectedTimeRange: selectedRange
    });
  },

  /**
   * 确认时间选择
   */
  confirmTimePicker() {
    if (!this.data.selectedTimeRange) {
      wx.showToast({
        title: '请选择配送时间',
        icon: 'none'
      });
      return;
    }

    const selectedTime = this.data.selectedTimeRange; // 获取时间范围的开始时间
    console.log(selectedTime)

    this.setData({
      showTimePicker: false,
      'order.anticipateAt': selectedTime
    });

    // 调用API更新订单的期望送达时间
    wx.showLoading({
      title: '更新中...'
    });

    util.callContainerApi(`/order/anticipate?orderId=${this.data.order.id}&anticipateAt=${selectedTime}`, "POST", null)
      .then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '送达时间已更新',
          icon: 'success'
        });
      }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: '更新失败',
          icon: 'error'
        });
        console.error('更新期望送达时间失败', err);
      });
  },

  /**
   * 取消时间选择
   */
  cancelTimePicker() {
    this.setData({
      showTimePicker: false,
      selectedTimeRange: null
    });
  },


  /**
   * 处理时间选择变化
   */
  bindTimeChange(e) {
    const index = e.detail.value;
    const selectedTime = this.data.timeRanges[index];

    this.setData({
      selectedTimeIndex: index,
      showTimePicker: false,
      'order.anticipateAt': selectedTime
    });

    // 调用API更新订单的期望送达时间
    wx.showLoading({
      title: '更新中...'
    });
    util.callContainerApi(`/order/updateAnticipateAt?orderId=${this.data.order.id}&anticipateAt=${selectedTime}`, "POST", null)
      .then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '送达时间已更新',
          icon: 'success'
        });
      }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: '更新失败',
          icon: 'error'
        });
        console.error('更新期望送达时间失败', err);
      });
  },

  /**
   * 更新订单地址信息
   */
  updateOrderAddress(address) {
    if (!address) return;

    const {
      order
    } = this.data;

    // 更新订单的地址信息
    order.addressId = address.id;
    order.receiveName = address.name;
    order.Phone = address.phone;
    order.address = address.address
    order.region = address.region

    this.setData({
      order
    });

    // 调用云函数更新订单地址
    wx.showLoading({
      title: '更新地址中...'
    });


    // 目前仅模拟更新成功
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '地址更新成功',
        icon: 'success'
      });
    }, 500);
  },


  /**
   * 支付订单
   */
  async payOrder() {
    if (!this.data.selectedTimeRange && !this.data.order.anticipateAt) {
      wx.showToast({
        title: '请选择配送时间',
        icon: 'none'
      });
      this.setData({
        showTimePicker: true
      })
      return;
    }
    const orderId = this.data.order.id;
    const totalPrice = this.data.order.totalPrice;
    //拉起支付
    util.pay(totalPrice, orderId,
      (paymentRes) => {
        // 请求订阅消息授权
        wx.requestSubscribeMessage({
          tmplIds: ['OO3j2utKf6Poaq3Hw7cf_lDqM7io-sbukgrfhvMbnm8', 'r8xfUwRwYtKDoJ8YWRP1ProZqNgabG_LmnVfUuvCtDs'],
          success(res) {
            console.log('订阅消息授权结果：', res)
          }
        });
        wx.showLoading({
          title: '支付中...'
        });
        util.callContainerApi(`/order/pay?orderId=${orderId}`, "POST", null)
          .then(res => {
            util.showSuccessToast("支付成功")
            // 支付成功后延迟跳转，确保用户看到提示
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/orderList/orderList?tab=待收货'
              });
            }, 1500);
          }).catch(err => {
            wx.hideLoading();
            util.showErrorToast("支付失败")
            console.error('支付失败', err);
          });
        wx.hideLoading();
      });

    // 重新加载订单数据
    setTimeout(() => {
      this.loadOrderData(orderId);
    }, 1500);
  },

  confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.id;
    util.callContainerApi(`/order/finish?orderid=${orderId}`, "POST", null)
      .then(res => {
        wx.showToast({
          title: '确认收货成功',
          icon: 'success'
        });
      })
  },
})